<template>
  <div>
    <div v-if="token">
      已经登陆，<router-link to="/">请前往首页</router-link>
    </div>
    <el-card
      shadow="hover"
      :body-style="{ padding: '20px' }"
      class="login"
      v-else
    >
      <div slot="header">
        <span>登陆页面</span>
      </div>
      <el-form
        :model="form"
        ref="loginRef"
        :rules="rules"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="onSubmit('loginRef')"
            :loading="isloading"
            >立即登陆</el-button
          >
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { Message } from 'element-ui'
import { mapState } from 'vuex'

export default {
  computed: {
    ...mapState({
      token: state => state.user.token
    })
  },
  data() {
    return {
      isloading: false,
      form: {
        username: "admin",
        password: "admin"
      },
      rules: {
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    onSubmit(formName) {
      this.isloading = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$store.dispatch('user/login', this.form).then(res => {
            this.isloading = false
            Message({
              type: 'success',
              message: '登陆成功'
            })
            this.$router.push('/')
          })
        } else {
          console.log('error submit!!')
          Message({
            type: 'error',
            message: '登陆失败'
          })
          this.isloading = false
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.login {
  width: 36rem;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>